import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import api from '../utils/api';
import { RequestError } from '../utils/request';
import { deleteByPrefix } from '../utils/oss';
import { userStorage } from '../utils/storage';
import './PageCommon.css';
import './CourseManagement.css';

function CourseManagement() {
  const navigate = useNavigate();
  const location = useLocation();
  const [courses, setCourses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  // 添加学员对话框状态
  const [showAddStudentDialog, setShowAddStudentDialog] = useState(false);
  const [selectedCourse, setSelectedCourse] = useState(null);
  const [studentPhone, setStudentPhone] = useState('');
  const [submitting, setSubmitting] = useState(false);

  // 使用 ref 防止重复调用
  const isFetchingRef = useRef(false);
  const prevPathRef = useRef(null);

  // 获取课程列表 - 首次加载和路由变化时调用
  useEffect(() => {
    const currentPath = location.pathname;
    const prevPath = prevPathRef.current;

    // 首次加载或从其他页面返回到课程管理页面时刷新
    if (currentPath === '/main/course') {
      // 首次加载（prevPath 为 null）或从其他路径返回时刷新
      if (prevPath === null || prevPath !== currentPath) {
        fetchCourseList();
      }
      prevPathRef.current = currentPath;
    } else {
      // 记录当前路径，以便下次返回时判断
      prevPathRef.current = currentPath;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [location.pathname]);

  const fetchCourseList = async () => {
    // 防止重复调用
    if (isFetchingRef.current) {
      console.log('正在获取课程列表，跳过重复调用');
      return;
    }

    try {
      isFetchingRef.current = true;
      setLoading(true);
      setError(null);

      // 使用 storage.js 的 getUserInfo，会自动检查过期时间
      const userInfo = userStorage.getUserInfo();
      if (!userInfo) {
        setError('未获取到用户信息，请重新登录');
        navigate('/login');
        return;
      }

      const phone = userInfo.phone;
      const role = userInfo.role; // 获取用户身份

      if (!phone) {
        setError('用户手机号不存在，请重新登录');
        navigate('/login');
        return;
      }

      console.log('查询课程列表，手机号:', phone, '身份:', role);

      // 根据身份调用不同的接口
      let result;
      if (role === 'admin') {
        // 管理员调用获取所有课程列表接口
        console.log('管理员身份，获取所有课程列表');
        result = await api.course.getAdminCoursesList();
      } else {
        // 教师调用获取教师课程列表接口
        console.log('教师身份，获取教师课程列表');
        result = await api.course.getTeacherCoursesList(phone);
      }
      
      console.log('课程列表结果:', result);

      // 处理结果（根据实际返回格式调整）
      if (Array.isArray(result)) {
        setCourses(result);
      } 

    } catch (error) {
      console.error('获取课程列表失败:', error);
      if (error instanceof RequestError) {
        setError(error.message);
      } else {
        setError('获取课程列表失败，请重试');
      }
    } finally {
      setLoading(false);
      isFetchingRef.current = false;
    }
  };

  const handleCreateCourse = () => {
    // 跳转到创建课程页面
    navigate('/main/create-course');
  };

  const handleAddStudent = (course) => {
    console.log('添加学员:', course);
    setSelectedCourse(course);
    setStudentPhone('');
    setShowAddStudentDialog(true);
  };

  const handleCloseDialog = () => {
    setShowAddStudentDialog(false);
    setSelectedCourse(null);
    setStudentPhone('');
    setSubmitting(false);
  };

  const handleSubmitAddStudent = async () => {
    // 验证手机号
    if (!studentPhone.trim()) {
      alert('请输入学员手机号');
      return;
    }

    // 简单的手机号格式验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(studentPhone.trim())) {
      alert('请输入正确的手机号格式');
      return;
    }

    setSubmitting(true);

    try {
      console.log('添加学员到课程:', {
        courseId: selectedCourse._id,
        courseName: selectedCourse.courseName,
        phone: studentPhone.trim()
      });

      // 调用添加学员接口
      await api.course.addStudentToCourse(selectedCourse._id, studentPhone.trim());

      alert(`成功添加学员 ${studentPhone} 到课程 "${selectedCourse.courseName}"`);
      
      // 关闭对话框并刷新列表
      handleCloseDialog();
      fetchCourseList();

    } catch (error) {
      console.error('添加学员失败:', error);
      if (error instanceof RequestError) {
        alert(`添加学员失败: ${error.message}`);
      } else {
        alert('添加学员失败，请重试');
      }
    } finally {
      setSubmitting(false);
    }
  };

  const handleEditCourse = (course) => {
    console.log('编辑课程:', course);
    // 跳转到编辑课程页面，将课程ID放在URL中
    navigate(`/main/edit-course/${course._id}`);
  };

  const handleDeleteCourse = async (course) => {
    if (!window.confirm(`确定要删除课程"${course.courseName}"吗？\n删除后将无法恢复！`)) {
      return;
    }
    
    try {
      console.log('删除课程:', course);
      
      // 1. 先删除数据库中的课程记录
      await api.course.removeCourseById(course._id);
      
      // 2. 删除OSS上的文件（等待完成，确保文件被删除）
      try {
        await deleteOSSFiles(course);
        console.log('OSS文件删除成功');
      } catch (ossError) {
        // OSS删除失败不影响数据库删除，但记录错误
        console.error('OSS文件删除失败:', ossError);
        // 提示用户OSS文件可能未完全删除
        alert(`课程"${course.courseName}"已从数据库删除，但部分OSS文件可能未完全清理。\n请检查OSS存储或联系管理员。`);
      }
      
      alert(`课程"${course.courseName}"已成功删除`);
      
      // 3. 刷新课程列表
      fetchCourseList();
      
    } catch (error) {
      console.error('删除课程失败:', error);
      if (error instanceof RequestError) {
        alert(`删除课程失败: ${error.message}`);
      } else {
        alert('删除课程失败，请重试');
      }
    }
  };

  // 删除OSS文件
  const deleteOSSFiles = async (course) => {
    // 获取教师手机号（优先使用课程中的teacherPhone）
    let teacherPhone = course.teacherPhone;
    
    // 如果课程对象中没有teacherPhone，尝试从storage获取当前用户手机号
    if (!teacherPhone) {
      const userInfo = userStorage.getUserInfo();
      if (userInfo && userInfo.phone) {
        teacherPhone = userInfo.phone;
      }
    }

    if (!teacherPhone) {
      const errorMsg = '无法获取教师手机号，无法删除OSS文件';
      console.error(errorMsg);
      throw new Error(errorMsg);
    }

    const courseId = course._id;
    console.log(`开始删除OSS文件: teacherPhone=${teacherPhone}, courseId=${courseId}`);
    
    const deleteResults = {
      thumbs: null,
      videos: null,
      errors: []
    };
    
    try {
      // 删除封面和海报（thumbs目录）
      const thumbsPrefix = `thumbs/${teacherPhone}/${courseId}/`;
      console.log('删除封面和海报:', thumbsPrefix);
      deleteResults.thumbs = await deleteByPrefix(thumbsPrefix);
      console.log(`封面和海报删除完成，删除了 ${deleteResults.thumbs.count} 个文件`);
    } catch (error) {
      const errorMsg = `删除封面和海报失败: ${error.message}`;
      console.error(errorMsg);
      deleteResults.errors.push(errorMsg);
      // 继续执行，不中断
    }
    
    try {
      // 删除视频（videos目录）
      const videosPrefix = `videos/${teacherPhone}/${courseId}/`;
      console.log('删除视频文件:', videosPrefix);
      deleteResults.videos = await deleteByPrefix(videosPrefix);
      console.log(`视频文件删除完成，删除了 ${deleteResults.videos.count} 个文件`);
    } catch (error) {
      const errorMsg = `删除视频文件失败: ${error.message}`;
      console.error(errorMsg);
      deleteResults.errors.push(errorMsg);
      // 继续执行，不中断
    }
    
    // 如果有错误，抛出异常
    if (deleteResults.errors.length > 0) {
      throw new Error(`OSS文件删除部分失败: ${deleteResults.errors.join('; ')}`);
    }
    
    const totalDeleted = (deleteResults.thumbs?.count || 0) + (deleteResults.videos?.count || 0);
    console.log(`课程"${course.courseName}"的OSS文件删除成功，共删除 ${totalDeleted} 个文件`);
    
    return deleteResults;
  };

  return (
    <div className="page-container">
      <div className="page-header">
        <h2>课程管理</h2>
        <button className="create-btn" onClick={handleCreateCourse}>
          新建课程
        </button>
      </div>
      <div className="page-content">
        {loading && (
          <div className="loading-container">
            <div className="loading-spinner"></div>
            <p>加载中...</p>
          </div>
        )}

        {error && (
          <div className="error-container">
            <p className="error-message">❌ {error}</p>
            <button className="retry-btn" onClick={fetchCourseList}>
              重试
            </button>
          </div>
        )}

        {!loading && !error && courses.length === 0 && (
          <div className="empty-container">
            <div className="empty-icon">📚</div>
            <p className="empty-text">暂无课程</p>
            <p className="empty-hint">点击右上角"新建课程"按钮创建第一个课程</p>
          </div>
        )}

        {!loading && !error && courses.length > 0 && (
          <div className="course-list">
            {courses.map((course) => (
              <div key={course._id} className="course-card">
                <div className="course-cover">
                  {course.courseThumb ? (
                    <img 
                      src={course.courseThumb} 
                      alt={course.courseName}
                      onError={(e) => {
                        e.target.style.display = 'none';
                        e.target.nextSibling.style.display = 'flex';
                      }}
                    />
                  ) : null}
                  <div className="course-cover-placeholder" style={{ display: course.courseThumb ? 'none' : 'flex' }}>
                    <span>📚</span>
                  </div>
                </div>
                
                <div className="course-info">
                  <h3 className="course-name" title={course.courseName}>
                    {course.courseName}
                  </h3>
                  <p className="course-id">ID: {course._id}</p>
                  {course.courseDesc && (
                    <p className="course-desc" title={course.courseDesc}>
                      {course.courseDesc}
                    </p>
                  )}
                  {course.courseVideos && course.courseVideos.length > 0 && (
                    <p className="course-videos">
                      🎬 {course.courseVideos.length} 个视频
                    </p>
                  )}
                  {course.courseMembers && course.courseMembers.length > 0 && (
                    <p className="course-members">
                      👥 {course.courseMembers.length} 名学生
                    </p>
                  )}
                </div>

                <div className="course-actions">
                  <button 
                    className="action-btn add-student-btn"
                    onClick={() => handleAddStudent(course)}
                  >
                    添加学员
                  </button>
                  <button 
                    className="action-btn edit-btn"
                    onClick={() => handleEditCourse(course)}
                  >
                    编辑课程
                  </button>
                  <button 
                    className="action-btn delete-btn"
                    onClick={() => handleDeleteCourse(course)}
                  >
                    删除课程
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 添加学员对话框 */}
      {showAddStudentDialog && (
        <div className="dialog-overlay" onClick={handleCloseDialog}>
          <div className="dialog-content" onClick={(e) => e.stopPropagation()}>
            <div className="dialog-header">
              <h3>添加学员</h3>
              <button className="dialog-close-btn" onClick={handleCloseDialog}>
                ✕
              </button>
            </div>
            
            <div className="dialog-body">
              <p className="dialog-course-info">
                课程：<strong>{selectedCourse?.courseName}</strong>
              </p>
              <div className="form-group">
                <label>学员手机号</label>
                <input
                  type="tel"
                  className="phone-input"
                  placeholder="请输入学员手机号"
                  value={studentPhone}
                  onChange={(e) => setStudentPhone(e.target.value)}
                  maxLength="11"
                  autoFocus
                  onKeyPress={(e) => {
                    if (e.key === 'Enter') {
                      handleSubmitAddStudent();
                    }
                  }}
                />
                <p className="input-hint">请输入11位手机号码</p>
              </div>
            </div>

            <div className="dialog-footer">
              <button 
                className="dialog-btn cancel-btn" 
                onClick={handleCloseDialog}
                disabled={submitting}
              >
                取消
              </button>
              <button 
                className="dialog-btn submit-btn" 
                onClick={handleSubmitAddStudent}
                disabled={submitting}
              >
                {submitting ? '提交中...' : '提交'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default CourseManagement;

